layui.use(['table', 'admin', 'ax', 'func','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var form = layui.form;

    var lastday = 3;

    //当前月份
    var thisdate = new Date();
    if(thisdate.getDate()<lastday){
        thisdate.setMonth(thisdate.getMonth()-1);
    }
    let monthNum = thisdate.getMonth() + 1;
    const month = thisdate.getFullYear() + "-" + (monthNum < 10 ? "0" + monthNum : monthNum);

    //考勤期间判断,默认在非考勤期间
    var buttonValid = false;
    //考勤期间
    var attendMonthValid = "";

    var synchronousMonth = "";
    //渲染时间选择框
    laydate.render({
        elem: "#month",
        value: month,
        type: 'month',
        tiger: 'click'
    });

    /**
     * 管理
     */
    var AttendAuditBtyArea = {
        tableId: "attendAuditBtyAreaTable"
    };



    /**
     * 初始化表格的列
     */
    AttendAuditBtyArea.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            {field: 'bh', hide: true, sort: false, title: '编号'},
            {field: 'dm', sort: false, title: '店名',width: 220, fixed: true, style: 'text-align: left'},
            {field: 'dz', hide: true, sort: false, title: '店长'},
            {field: 'dh', hide: true, sort: false, title: '店长电话'},
            {field: 'kqDz', sort: false, title: '考勤店长',width: 90},
            {field: 'kqDh', sort: false, title: '考勤店长电话',width: 120},
            {field: 'attendMonth', sort: false, title: '考勤月份',width: 90},
            {field: 'auditStatus', sort: false,  templet: '#auditStatusTmp',title: '状态',width: 80},
            {field: 'yyjl', sort: false, title: '营运经理',width: 90},
            {field: 'dd', sort: false, title: '督导',width: 80},
            {field: 'ddSupervisorPhone', sort: false, title: '督导联系方式',width: 120},
            {field: 'xm', sort: false, title: '大店长',width: 80},
            {field: 'id',  hide: true, title: 'id'},
            {field: 'bz', sort: false, title: '备注',width: 120},
            {field: 'flag', hide: true,sort: false, title: '标记'},
            {field: 'gz', hide: true, sort: false, title: ''},
            {field: 'flagd', hide: true, sort: false, title: ''},
            {field: 'qtgz', hide: true, sort: false, title: ''},
            {field: 'qt', hide: true, sort: false, title: ''},
            {field: 'submitMonth',hide: true, sort: false, title: '提交月份'},
            {field: 'dm',hide: true,sort: false, title: '店名'},
            {field: 'managerName',hide: true, sort: false, title: '店长名字'},
            {field: 'managerPhone',hide: true,sort: false, title: '店长联系方式'},
            {field: 'managerId',hide: true, sort: false, title: '店长id'},
            {field: 'ddSupervisorName',hide: true,sort: false, title: '督导名字'},
            {field: 'ddSupervisorPhone',hide: true,sort: false, title: '督导联系方式'},
            {field: 'ddSupervisorId',hide: true, sort: false, title: '督导id'},

            {field: 'btyAreaBh',hide: true, sort: false, title: '编号'},
            {field: 'btyAreaId',hide: true, sort: false, title: '店id'},
            {align: 'center',toolbar: '#tableBar', title: '操作', fixed: "right", style: 'text-align: right'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    AttendAuditBtyArea.search = function () {
        var queryData = {};
        var attendMonth= $("#month").val();
        if(attendMonth){
            queryData['attendMonth'] = attendMonth.replace("-","");
        }else{
            //当前月份
            var thisdate = new Date();
            if(thisdate.getDate()<lastday){
                thisdate.setMonth(thisdate.getMonth()-1);
            }
            let monthNum = thisdate.getMonth() + 1;
            const month = thisdate.getFullYear() + "-" + (monthNum < 10 ? "0" + monthNum : monthNum);
            queryData['attendMonth'] = month.replace("-","");
            $("#month").val(month);
        }


        queryData['dm'] = $("#dm").val();
        queryData['kqDz'] = $("#kqDz").val();
        queryData['kqDh'] = $("#kqDh").val();
        queryData['dd'] = $("#dd").val();
        queryData['ddSupervisorPhone'] = $("#ddSupervisorPhone").val();
        queryData['auditStatus'] = $("#auditStatus").val();
        queryData['yyjl'] = $("#yyjl").val();
        table.reload(AttendAuditBtyArea.tableId, {
            where: queryData, page: {curr: 1}
        });
        AttendAuditBtyArea.searchSumValue($("#month").val().replace("-",""));
    };
    /**
     * 点击查询合计值
     */
    AttendAuditBtyArea.searchSumValue = function (month) {
        var queryData = {};
        queryData['attendMonth'] = month.replace("-","");
        $.ajax({
            type: "post",
            url: "/attendAuditBtyArea/searchSumValue",
            datatype: "json",
            async: false,
            data:queryData,
            success: function (data) {
                console.log(data);
                if(data){
                    // if(data.BtyAreaAttendMonth){
                    //     $("#sumValue").html(data.BtyAreaAttendMonth+",完成考勤店数量<span style='font-size: 18px;'>"+data.BtyAreaSubmitThrough+"家</span>，未完成考勤店数量<span style='font-size: 18px;'>"+data.BtyAreaNotThrough+"家</span>");
                    //     $("#sumNnfinishedValue").html(data.BtyAreaAttendMonth+",未完成考勤店中，店长未创建考勤<span style='font-size: 18px;'>"+data.BtyAreaNotCreate+"家</span>（包含督导未指定店长<span style='font-size: 18px;'>"+data.BtyAreaNotKqdz+"家</span>）,店长未提交<span style='font-size: 18px;'>"+data.BtyAreaNotSubmit+"家</span>，店长提交督导未审核<span style='font-size: 18px;'>"+data.BtyAreaSubmitAudit+"家</span>，提交被驳回未提交<span style='font-size: 18px;'>"+data.BtyAreaSubmitBack+"家</span>。");
                    // }else{
                    //     $("#sumValue").html("缺少有效的查询条件，考勤月份，无法进行统计查询。");
                    //     $("#sumNnfinishedValue").html("缺少有效的查询条件，考勤月份，无法进行统计查询。");
                    // }
                    // if(data.BtyAreaAll){
                    //     $("#newShopSumValue").html("档案最新门店数量共计:<span style='font-size: 18px;'>"+data.BtyAreaAll+"家</span>门店(此为最新档案数据，不和月份查询条件一致)");
                    // }
                    if(data.BtyAreaAll){
                        $("#BtyAreaAll").html(data.BtyAreaAll);
                    }
                    if(data.BtyAreaAttendMonth){

                        $("#BtyAreaAttendMonth").html(data.BtyAreaAttendMonth);

                        $("#BtyAreaSubmitThrough").html(data.BtyAreaSubmitThrough);
                        $("#BtyAreaNotThrough").html(data.BtyAreaNotThrough);

                        $("#BtyAreaNotCreate").html(data.BtyAreaNotCreate);
                        $("#BtyAreaNotKqdz").html(data.BtyAreaNotKqdz);
                        $("#BtyAreaNotSubmit").html(data.BtyAreaNotSubmit);
                        $("#BtyAreaSubmitAudit").html(data.BtyAreaSubmitAudit);
                        $("#BtyAreaSubmitBack").html(data.BtyAreaSubmitBack);
                    }
                }
            }
        });

    }
    /**
     * 获取是否允许考勤
     *
     * @param 获取是否允许考勤
     */
    AttendAuditBtyArea.getCreateAttendButton = function () {
        $.ajax({
            type: "post",
            url: "/attendAudit/getCreateAttendButton",
            datatype: "json",
            async: false,
            success: function (data) {
                if(data){
                    if(data.data.buttonValid == "0"){
                        buttonValid = true;
                        window.buttonValid = true;
                        attendMonthValid = data.data.attendMonth.replace("-","");
                        window.attendMonthValid = data.data.attendMonth.replace("-","");

                    }else{
                        buttonValid = false;
                        window.buttonValid = false;
                        attendMonthValid = data.data.attendMonth.replace("-","");
                        window.attendMonthValid = data.data.attendMonth.replace("-","");
                    }
                }
                console.log(data);
            }
        });
    };
    /**
     * 获取同步的月份
     *
     *
     */
    AttendAuditBtyArea.synchronousMonth = function (data) {
        $.ajax({
            type: "post",
            url: "/attendAuditBtyArea/getSynchronousMonth",
            datatype: "json",
            async: false,
            success: function (data) {
                synchronousMonth = data.data.synchronousMonth;
                window.synchronousMonth = data.data.synchronousMonth;
            },
            error: function (data) {
                Feng.error("失败!");
            }
        });
    };
    /**
     * 获取营运经理的列表
     *
     * @param 获取营运经理的列表
     */
    AttendAuditBtyArea.getYyjlList = function () {
        $.ajax({
            type: "post",
            url: "/attendAuditBtyArea/getYyjlList",
            datatype: "json",
            async: false,
            success: function (data) {

                //yyjl
                //初始化供货商
                $("#yyjl").html("<option value=''>全部营运经理</option>");
                $.each(data.data, function (index, val) {
                    $("#yyjl").append("<option value='" + val.yyjl + "'>" + val.yyjl+ "</option>");
                });
                form.render('select');
            }
        });
    };
    /**
     * 跳转到添加页面
     */
    AttendAuditBtyArea.jumpAddPage = function () {
        window.location.href = Feng.ctxPath + '/attendAuditBtyArea/add'
    };

    /**
    * 跳转到编辑页面
    *
    * @param data 点击按钮时候的行数据
    */
    AttendAuditBtyArea.jumpEditPage = function (data) {
        window.location.href = Feng.ctxPath + '/attendAuditBtyArea/edit?id=' + data.id
    };


    /**
     * 跳转到可能造成考勤异常的数据
     *
     * @param data 点击按钮时候的行数据
     */
    AttendAuditBtyArea.jumpWarningPage = function (data) {
        window.location.href = Feng.ctxPath + '/attendAuditBtyArea/attendAuditBtyArea_impact'
    };

    /**
     * 打开需要同步的页面
     */
    AttendAuditBtyArea.synchronousPage = function(){
        layer.open({
            type: 2,
            title: ['同步确认','font-weight:blod;text-align: center;padding-left:20px;'],
            area: ['450px', '240px'],
            skin: 'layerdemo',
            content: Feng.ctxPath + '/attendAuditBtyArea/synchronousPage',
            end: function () {
                AttendAuditBtyArea.synchronousMonth();
                AttendAuditBtyArea.search();
            }
        });
    }
    /**
     * 督导审核通过强制驳回，督导驳回
     * @param data
     */
    AttendAuditBtyArea.auditStatusToSubmitAudit=function(data){
        layer.open({
            type: 1,
            area: ['200px', '200px'],
            btnAlign: 'c',
            btn: ['确认', '取消'],
            content: '<p style="text-align: center;padding-top: 40px;">强制驳回到督导审核状态吗？</p>'
            ,yes: function(index, layero){
                var newData =data;
                $.ajax({
                    type: "post",
                    url: "/attendAuditBtyArea/auditStatusToSubmitAudit",
                    datatype: "json",
                    async: false,
                    data:data,
                    success: function (data) {
                        AttendAuditBtyArea.search();
                        Feng.success("成功!");
                        console.log(data);
                    }
                });
                //aaid

                layer.close(index);
            }
            ,btn2: function(index, layero){
                //按钮【按钮二】的回调
                //return false 开启该代码可禁止点击该按钮关闭
                layer.close(index);
            }
        });

    }

    /**
     * 考勤期间，未提交状态，更换店长
     *
     * @param 获取是否允许考勤
     */
    AttendAuditBtyArea.editDz = function(data){
        layer.open({
            type: 1,
            area: ['200px', '200px'],
            btnAlign: 'c',
            btn: ['确认', '取消'],
            content: '<p style="text-align: center;padding-top: 40px;">强制驳回到督导审核状态吗？</p>'
            ,yes: function(index, layero){


            }
            ,btn2: function(index, layero){
                //按钮【按钮二】的回调
                //return false 开启该代码可禁止点击该按钮关闭
                layer.close(index);
            }
        });
    }


    /**
     * 导出excel按钮
     */
    AttendAuditBtyArea.exportExcel = function () {
        var checkRows = table.checkStatus(AttendAuditBtyArea.tableId);
        if (checkRows.data.length === 0) {
            // Feng.error("请选择要导出的数据");
            //获取导出Excel的数据
            // var ajax = new $ax(Feng.ctxPath + "/archives/listExport");
            // var result = ajax.start();
            // var lists=result;

            var queryData = {};
            var attendMonth= $("#month").val();
            if(attendMonth){
                queryData['attendMonth'] = attendMonth.replace("-","");
            }else{
                //当前月份
                var thisdate = new Date();
                if(thisdate.getDate()<lastday){
                    thisdate.setMonth(thisdate.getMonth()-1);
                }
                let monthNum = thisdate.getMonth() + 1;
                const month = thisdate.getFullYear() + "-" + (monthNum < 10 ? "0" + monthNum : monthNum);
                queryData['attendMonth'] = month.replace("-","");
                $("#month").val(month);
            }


            queryData['dm'] = $("#dm").val();
            queryData['kqDz'] = $("#kqDz").val();
            queryData['kqDh'] = $("#kqDh").val();
            queryData['dd'] = $("#dd").val();
            queryData['ddSupervisorPhone'] = $("#ddSupervisorPhone").val();
            queryData['auditStatus'] = $("#auditStatus").val();
            queryData['yyjl'] = $("#yyjl").val();

            $.ajax({
                type: "post",
                url: "/attendAuditBtyArea/listAttendAuditForExport",
                datatype: "json",
                async: false,
                data:queryData,
                success: function (data) {
                    lists = data.data;
                    table.exportFile(tableResult.config.id, lists, 'xls');
                }
            });



        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    AttendAuditBtyArea.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/attendAuditBtyArea/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(AttendAuditBtyArea.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    // 渲染表格
    // var tableResult = table.render({
    //     elem: '#' + AttendAuditBtyArea.tableId,
    //     url: Feng.ctxPath + '/attendAuditBtyArea/list',
    //     page: true,
    //     height: "full-158",
    //     cellMinWidth: 100,
    //     cols: AttendAuditBtyArea.initColumn()
    // });

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + AttendAuditBtyArea.tableId,
        url: Feng.ctxPath + '/attendAuditBtyArea/listAttendAudit',
        page: true,
        limit:20,
        height: "full-231",
        cellMinWidth: 100,
        cols: AttendAuditBtyArea.initColumn()
    });
    // 重置按钮事件
    $('#btnReset').click(function () {
        $('#dm').val('');
        $('#kqDz').val('');
        $('#kqDh').val('');
        $('#dd').val('');
        $("#ddSupervisorPhone").val('');
        $("#yyjl").val('');
        $("#auditStatus").val('');

        $("#month").val(month);
        AttendAuditBtyArea.search();
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        AttendAuditBtyArea.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

        AttendAuditBtyArea.jumpAddPage();

    });

    // 导出excel
    $('#btnExp').click(function () {
        AttendAuditBtyArea.exportExcel();
    });

    // 导出跳转到警告的页面
    $('#btnWarning').click(function () {

        AttendAuditBtyArea.jumpWarningPage();
    });

    //  跳转到同步页面
    $('#synchronousAttendEmployeeMonthToBtyArchives').click(function () {
        AttendAuditBtyArea.synchronousPage();
    });



    // 工具条点击事件
    table.on('tool(' + AttendAuditBtyArea.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            AttendAuditBtyArea.jumpEditPage(data);
        } else if (layEvent === 'delete') {
            AttendAuditBtyArea.onDeleteItem(data);
        } else if(layEvent === 'auditStatusToSubmitAudit'){
            AttendAuditBtyArea.auditStatusToSubmitAudit(data);
        } else if(layEvent === 'editDz'){
            AttendAuditBtyArea.editDz(data);
        }

    });

    //初始化页面
    $(function () {
        AttendAuditBtyArea.getCreateAttendButton();
        AttendAuditBtyArea.synchronousMonth();
        AttendAuditBtyArea.getYyjlList();
        //var attendMonth = $("#month").val();
        //AttendAudit.search();
        setTimeout(() =>{
            AttendAuditBtyArea.search();
        },100);

    });
});
